<template>
  <el-row class="RangeDrawer">
    <commonDrawer
      :title="drawerType === 'add' ? '新增过滤器' : '编辑过滤器'"
      :drawer="drawer"
      :size="900"
      :isShowMoreBtn="true"
      @closeDraw="closeDraw"
      @cancelFun="closeDraw"
      @save="save"
    >
      <template slot="column">
        <div class="range-area" v-loading="loading">
          <el-form
            ref="formRef"
            :model="form"
            class="m7-form"
            label-position="top"
            :rules="rules"
          >
            <el-form-item label="过滤器名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入过滤器名称"
                :maxlength="20"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item v-show="this.form.category !== 'system'">
              <span slot="label"
                ><span style="color: #f56c6c; margin-right: 4px">*</span
                >过滤器条件</span
              >
              <FilterConfig ref="FilterConfig"></FilterConfig>
            </el-form-item>
            <el-form-item label="过滤器状态" prop="enabled">
              <el-switch v-model="form.enabled"></el-switch>
            </el-form-item>
            <el-form-item label="权限配置" prop="visibleScopeType">
              <el-radio-group v-model="form.visibleScopeType" @change="changeVisibleScopeType">
                <el-radio label="role">按角色</el-radio>
                <el-radio label="dept">按部门</el-radio>
                <el-radio label="user">按人员</el-radio>
                <el-radio label="all">所有人</el-radio>
              </el-radio-group>
              <div style="margin-bottom:10px"></div>
              <el-select v-model="form.visibleScopes" filterable multiple size="small" placeholder="请选择" v-show="form.visibleScopeType === 'role'" style="width:100%">
                <el-option
                  v-for="item in roles"
                  :key="item._id"
                  :label="item.name"
                  :value="item._id"
                >
                </el-option>
              </el-select>
              <el-cascader
              :clearable="true"
              style="width:100%"
              size="small"
              filterable
              v-show="form.visibleScopeType === 'dept'"
              v-model="form.visibleScopes"
              :options="departmentTree"
              :props="{ multiple: true, checkStrictly: true, label: 'name', value: '_id', emitPath: false }"
              :show-all-levels="true"
              :collapse-tags="false"
              placeholder="请选择">
            </el-cascader>
            <AgentTransfer v-show="form.visibleScopeType === 'user'" ref="AgentTransfer"></AgentTransfer>
            </el-form-item>
          </el-form>
        </div>
      </template>
    </commonDrawer>
  </el-row>
</template>

<script lang="ts">
/**
 * 过滤器编辑组件
 */
import { Component, Vue, Ref } from 'vue-property-decorator';
import commonDrawer from '@/components/globalTool/resizeDrawer/drawer.vue';
import { commonAction, deepClone } from '@/utils/common';
import AgentTransfer from '@/views/newCustomer/common/agentTransfer.vue'
import FilterConfig from './FilterConfig.vue'
@Component({
  name: 'EditFields',
  components: {
    commonDrawer,
    AgentTransfer,
    FilterConfig
  }
})
export default class EditFields extends Vue {
  [x: string]: any
  @Ref() private readonly FilterConfig: any
  @Ref() private readonly AgentTransfer: any
  private drawer: boolean = false
  private drawerType: string = 'add'
  private data: any
  private loading: boolean = false
  private form: any = {
    name: '',
    enabled: false,
    visibleScopeType: 'role',
    visibleScopes: [],
    conditionGroups: [] // 条件组
  }

  private search = {
    word: '',
    dept: []
  }

  private rules = {
    name: [{ required: true, trigger: 'change', message: '请输入过滤器名称' }]
  }

  private async openDraw (data: any, type: string) {
    this.drawer = true;
    this.$nextTick(() => {
      this.drawerType = type
      if (type === 'add') {
        this.form = {
          name: '',
          enabled: false,
          visibleScopeType: 'role',
          visibleScopes: [],
          conditionGroups: [] // 条件组
        }
      } else {
        this.form = { ...this.form, ...data }
      }
      this.FilterConfig.setData(data.conditionGroups || [], type)
      this.AgentTransfer.setData(data.visibleScopes || [])
    })
  }

  get roles () {
    return this.$store.state.common.publicCache.roleList
  }

  get departmentTree () {
    return this.$store.state.common.publicCache.departmentTree.tree
  }

  get userList () {
    const agents = deepClone(this.$store.state.common.publicCache.userListObj)
    const agentsArr: any = []
    for (const i in agents) {
      agentsArr.push({ key: agents[i]._id, label: agents[i].name, department: agents[i].departmentConfig ? agents[i].departmentConfig.departmentIdList : [] })
    }
    return agentsArr
  }

  private changeVisibleScopeType () {
    this.form.visibleScopes = []
  }

  private closeDraw () {
    this.drawer = false
  }

  private handleFrom () { // 提交表单前，整理表单
    if (this.form.visibleScopeType === 'user') { // 选择按人员的时候，
      this.form.visibleScopes = this.AgentTransfer.getData()
    } else if (this.form.visibleScopeType === 'all') { // 选择所有人的时候
      this.form.visibleScopes = []
    }
    let flag = false
    const filterData = this.FilterConfig.getData()
    filterData.forEach(item => {
      if (item.andConditions && item.andConditions.length <= 0 && item.orConditions && item.orConditions.length <= 0) { // 且和或的条件都是空数组
        flag = true
      }
      Object.keys(item).forEach((conditionItem: any) => {
        if (item[conditionItem] && typeof item[conditionItem] === 'object') {
          item[conditionItem].forEach(andItem => {
            andItem.field = andItem.fieldObj.field
            if (typeof andItem.value === 'string' || typeof andItem.value === 'number') {
              if (andItem.value === '') {
                andItem.value = []
              } else {
                andItem.value = [andItem.value]
              }
            }
            if (andItem.operator === 'between' && andItem.value2) { // 条件是介于，并且是有第二个绑定值
              andItem.value = [...andItem.value, ...[andItem.value2]]
            }
            delete andItem.value2
            if (!andItem.field || !andItem.operator || (andItem.value && andItem.value.length <= 0 && !['empty', 'nempty'].includes(andItem.operator))) { // 没有选择字段 || 条件 || 值
              flag = true
            }
            delete andItem.fieldObj
          })
        }
      })
    })
    if (flag) {
      this.$message.error('请检查您的过滤器条件')
      return false
    }
    // if (this.form.visibleScopeType !== 'all' && this.form.visibleScopes.length <= 0) {
    //   this.$message.error('请检查您的权限配置')
    //   return false
    // }
    this.form.conditionGroups = filterData
    return true
  }

  private save () {
    (this as any).$refs.formRef.validate(async (valid) => {
      if (valid) {
        const result = this.handleFrom()
        if (!result) {
          return false
        }
        let actionUrl = '/server-crm/action/config/customer/filter/update'
        if (this.drawerType === 'add') {
          actionUrl = '/server-crm/action/config/customer/filter/create'
        }
        commonAction({ url: actionUrl, method: 'POST', data: this.form }).then(resp => {
          if (resp && resp.success) {
            this.$message.success('保存成功')
            this.closeDraw()
            this.$emit('refresh')
          }
        })
      }
    })
  }

  private beforeMount () {
    this.$getCache('/base/action/general/cache/query', ['roleList'], true)
  }
}
</script>

<style lang="stylus" scoped>
.RangeDrawer
  .range-area
    .rightButton
      position absolute
      top 0px
      right 0px
      padding-top 0px
      height 12px
</style>
